﻿using IP扫描.Events;
using IP扫描.Models;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Net;

namespace IP扫描.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        private string _title = "IP扫描";
        public string Title
        {
            get { return _title; }
            set { SetProperty(ref _title, value); }
        }

        public ObservableCollection<LocalIPListClass> LocalIPList { get; set; }

        private LocalIPListClass localIP;

        public LocalIPListClass LocalIP
        {
            get { return localIP; }
            set
            {
                localIP = value;
                OnPropertyChanged(new PropertyChangedEventArgs("LocalIP"));
            }
        }

        protected override void OnPropertyChanged(PropertyChangedEventArgs args)
        {
            GlobalIP.IP = LocalIP.IP;
            string[] ips = LocalIP.IP.Split(new char[] { '.' }, System.StringSplitOptions.RemoveEmptyEntries);
            aggregator.GetEvent<MessengerEvent>().Publish(new IPClass()
            {
                N1 = ips[0],
                N2 = ips[1],
                N3 = ips[2],
                N4 = ips[3],
            });
            base.OnPropertyChanged(args);
        }

        private readonly IEventAggregator aggregator;
        public DelegateCommand<string> IPV4ScanCommand { get; set; }
        public DelegateCommand<string> IPPortScanCommand { get; set; }
        public MainWindowViewModel(IRegionManager manager,IEventAggregator eventAggregator)
        {
            aggregator = eventAggregator;

            LocalIPList = new ObservableCollection<LocalIPListClass>();

            IPV4ScanCommand = new DelegateCommand<string>((x) =>
            {
                manager.Regions["ContentRegion"].RequestNavigate(x);
            });
            IPPortScanCommand = new DelegateCommand<string>((x) =>
            {
                manager.Regions["ContentRegion"].RequestNavigate(x);
            });

            IPAddress[] ipads = Dns.GetHostAddresses(Dns.GetHostName(), System.Net.Sockets.AddressFamily.InterNetwork);
            foreach (var ip in ipads)
            {
                LocalIPList.Add(new LocalIPListClass()
                {
                     IP= ip.ToString()
                });
            }
        }
    }
}
